package com.siyoumi.app.modules.user.service;

import com.siyoumi.app.entity.SysCorpPay;
import com.siyoumi.app.entity.SysSale;
import com.siyoumi.app.modules.user.entity.EnumCorpPayState;
import com.siyoumi.app.modules.user.vo.VoCorpPayResetStatus;
import com.siyoumi.app.modules.user.vo.VoCorpPaySave;
import com.siyoumi.app.modules.user.vo.VoCorpPayUpdateStatus;
import com.siyoumi.app.service.SysCorpPayService;
import com.siyoumi.app.sys.service.wxapi.WxApiPay;
import com.siyoumi.app.sys.vo.BillOrderData;
import com.siyoumi.component.XApp;
import com.siyoumi.component.XBean;
import com.siyoumi.component.XEnumBase;
import com.siyoumi.component.XSpringContext;
import com.siyoumi.component.http.InputData;
import com.siyoumi.component.http.XHttpContext;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.mybatispuls.JoinWrapperPlus;
import com.siyoumi.service.IWebService;
import com.siyoumi.util.XDate;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import com.siyoumi.validator.XValidator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

//分销员
@Slf4j
@Service
public class SvcSysCorpPay
        implements IWebService {
    static public SvcSysCorpPay getBean() {
        return XSpringContext.getBean(SvcSysCorpPay.class);
    }

    static public SysCorpPayService getApp() {
        return SysCorpPayService.getBean();
    }

    public SysCorpPay getEntityByIdSrc(String idSrc) {
        JoinWrapperPlus<SysCorpPay> query = listQuery();
        query.eq("corppayq_id_src", idSrc);
        return getApp().first(query);
    }

    public JoinWrapperPlus<SysCorpPay> listQuery() {
        return listQuery(InputData.getIns());
    }

    /**
     * select
     *
     * @return query
     */
    public JoinWrapperPlus<SysCorpPay> listQuery(InputData inputData) {
        String uid = inputData.input("uid");
        String orderId = inputData.input("order_id");
        String state = inputData.input("state");
        String createBegin = inputData.input("create_begin");
        String createEnd = inputData.input("create_end");

        JoinWrapperPlus<SysCorpPay> query = getApp().join();
        query.eq("corppay_x_id", XHttpContext.getX());

        if (XStr.hasAnyText(uid)) { //uid
            query.eq("corppayq_uid", uid);
        }
        if (XStr.hasAnyText(state)) { //审核状态
            query.eq("corppayq_status", state);
        }
        if (XStr.hasAnyText(orderId)) { //订单号
            query.eq("corppayq_order_id", orderId);
        }
        if (XStr.hasAnyText(createBegin) && XStr.hasAnyText(createEnd)) { //创建时间
            LocalDateTime b = XDate.parse(createBegin);
            LocalDateTime e = XDate.parse(createEnd);

            query.between("corppay_create_date", b, e.plusDays(1).minusSeconds(1));
        }

        return query;
    }

    /**
     * 提现记录
     */
    public SysCorpPay save(VoCorpPaySave vo) {
        SysCorpPay entity = new SysCorpPay();
        XBean.copyProperties(vo, entity);
        entity.setCorppay_x_id(XHttpContext.getX());
        entity.setAutoID();

        XApp.getTransaction().execute(status -> {
            boolean save = getApp().getBean().save(entity);
            return save;
        });

        return entity;
    }

    /**
     * 更新商家处理状态
     */
    @Transactional(rollbackFor = Exception.class)
    public XReturn updateStoreStatus(VoCorpPayUpdateStatus vo) {
        SysCorpPay entity = getApp().getEntity(vo.getId());
        XValidator.isNull(entity, "id异常");
        if (entity.getCorppayq_status() != 0) {
            return XReturn.getR(20104, "记录已处理");
        }

        SysCorpPay entityUpdate = new SysCorpPay();
        XBean.copyProperties(vo, entityUpdate);
        entityUpdate.setCorppayq_status_date(XDate.now());
        getApp().saveOrUpdatePassEqualField(entity, entityUpdate);

        return EnumSys.OK.getR();
    }

    /**
     * 重置提现状态
     * 更换订单号
     */
    @Transactional(rollbackFor = Exception.class)
    public XReturn resetStatus(VoCorpPayResetStatus vo) {
        SysCorpPay entity = getApp().getEntity(vo.getId());
        XValidator.isNull(entity, "id异常");
        if (entity.getCorppayq_status() == 1) {
            return XReturn.getR(20128, "提现成功，不能重置状态");
        }

        XReturn r = payCheck(entity.getCorppayq_id_src());
        if (r.ok()) {
            return XReturn.getR(20138, "提现成功，不能重置状态");
        }

        SysSale entitySales = SvcSysSale.getBean().getEntitySaleByUid(entity.getCorppayq_uid());
        XValidator.err(SvcSysSale.getBean().valid(entitySales));

        SysCorpPay entityUpdate = new SysCorpPay();
        entityUpdate.setCorppay_true_name(entitySales.getSale_name());
        entityUpdate.setCorppayq_status(0);
        entityUpdate.setCorppayq_api_status("");
        entityUpdate.setCorppayq_order_id(XApp.getStrID("X"));
        entityUpdate.setCorppayq_status_date(XDate.date2000());
        getApp().saveOrUpdatePassEqualField(entity, entityUpdate);

        return EnumSys.OK.getR();
    }

    /**
     * 拉起提现
     *
     * @param id
     */
    public XReturn pay(String id) {
        SysCorpPay entity = getEntityByIdSrc(id);
        XValidator.isNull(entity, "id异常");
        if (entity.getCorppayq_status() != 0) {
            return XReturn.getR(20085, "订单已处理");
        }

        SysSale entitySales = SvcSysSale.getBean().getEntitySaleByUid(entity.getCorppayq_uid());
        XValidator.err(SvcSysSale.getBean().valid(entitySales));

        String sceneId = "1005";
        WxApiPay api = WxApiPay.getIns(XHttpContext.getXConfig());
        BillOrderData billOrderData = BillOrderData.of(entity.getCorppayq_openid(),
                entity.getCorppayq_order_id(),
                sceneId,
                entity.getCorppay_true_name(),
                entity.getCorppayq_fee(),
                entity.getCorppayq_desc());
        return api.billOrder(billOrderData);
    }

    /**
     * 检查提现情况
     * <p>
     * 转帐失败原因fail_reason
     * https://pay.weixin.qq.com/doc/v3/merchant/4013774966
     *
     * @param id
     */
    public XReturn payCheck(String id) {
        SysCorpPay entity = getEntityByIdSrc(id);
        XValidator.isNull(entity, "id异常");
        if (entity.getCorppayq_status() != 0) {
            return XReturn.getR(20085, "订单已处理");
        }

        WxApiPay api = WxApiPay.getIns(XHttpContext.getXConfig());
        XReturn r = api.billOrderInfo(entity.getCorppayq_order_id());
        if (r.ok()) {
            EnumCorpPayState enumState = XEnumBase.of(EnumCorpPayState.class); //状态中文翻译

            String state = r.getData("state");
            String stateStr = enumState.get(state);
            r.setErrCode(20095);
            r.setErrMsg(stateStr);

            if (!entity.getCorppayq_api_status().equals(state)) { //返回状态不一样，更新
                SysCorpPay entityUpdate = new SysCorpPay();
                entityUpdate.setCorppayq_api_status(state);
                entityUpdate.setCorppayq_status_date(XDate.now());
                entityUpdate.setCorppayq_return_str(stateStr);
                //更新微信订单号
                String orderIdWx = r.getData("transfer_bill_no");
                entityUpdate.setCorppayq_order_id_ex(orderIdWx);

                if ("SUCCESS".equals(state)) { //成功
                    entityUpdate.setCorppayq_status(1);
                    r.setErrCode(0);
                }
                if ("FAIL".equals(state)) { //失败
                    entityUpdate.setCorppayq_status(10);
                }
                getApp().saveOrUpdatePassEqualField(entity, entityUpdate);
            }
        }

        return r;
    }
}
